import React, {useState} from 'react';
import {
  Button,
  DeviceEventEmitter,
  NativeModules,
  StyleSheet,
  Text,
} from 'react-native';
import {
  CameraApi,
  CameraProps,
  CodeFormat,
  OnCaptureButtonPressInData,
  OnCaptureButtonPressOutData,
  OnError,
  OnOrientationChangeData,
  OnReadCodeData,
  OnZoom,
  Orientation,
} from '../types';
import NativeCamera, {CameraCommands} from './CameraKitNativeComponent';

const {CKCameraManager} = NativeModules;

const Camera = React.forwardRef<CameraApi, CameraProps>((props, ref) => {
  const {
    onOrientationChange,
    onZoom,
    onError,
    onReadCode,
    onCaptureButtonPressIn,
    onCaptureButtonPressOut,
    ...rest
  } = props;
  const nativeRef = React.useRef(null);

  const capture = (): Promise<any> => {
    return new Promise(resolve => {
      const onCodeScannedListener = DeviceEventEmitter.addListener(
        'onTaskPhoto',
        (data: any) => {
          resolve(data);
          onCodeScannedListener.remove();
        },
      );
      if (!nativeRef.current) throw new Error('nativeRef.current is NaN');
      CameraCommands.takePhoto(nativeRef.current);
    });
  };

  DeviceEventEmitter.addListener('onZoom', (zoom: OnZoom) => {
    // 添加事件处理
    onZoom?.(zoom);
  });
  DeviceEventEmitter.addListener('onError', (error: OnError) => {
    // 添加事件处理
    onError?.(error);
  });
  DeviceEventEmitter.addListener(
    'onOrientationChange',
    (orientation: OnOrientationChangeData) => {
      // 添加事件处理
      onOrientationChange?.(orientation);
    },
  );
  DeviceEventEmitter.addListener('onReadCode', (code: OnReadCodeData) => {
    // 添加事件处理
    onReadCode?.(code);
  });

  DeviceEventEmitter.addListener(
    'onCaptureButtonPressIn',
    (pressIn: OnCaptureButtonPressInData) => {
      // 添加事件处理
      onCaptureButtonPressIn?.(pressIn);
    },
  );

  DeviceEventEmitter.addListener(
    'onCaptureButtonPressOut',
    (pressOut: OnCaptureButtonPressOutData) => {
      // 添加事件处理
      onCaptureButtonPressOut?.(pressOut);
    },
  );

  React.useImperativeHandle(ref, () => ({
    capture,
    requestDeviceCameraAuthorization: async () => {
      return await CKCameraManager.checkDeviceCameraAuthorizationStatus();
    },
    checkDeviceCameraAuthorizationStatus: async () => {
      return await CKCameraManager.checkDeviceCameraAuthorizationStatus();
    },
  }));

  return (
    <>
      <NativeCamera ref={nativeRef} {...rest} />
    </>
  );
});

const styles = StyleSheet.create({
  text: {
    fontSize: 20,
    textAlign: 'center',
    color: '#000',
    marginTop: 10,
  },
});

export default Camera;
